'''
Created on Jul 21, 2011

@author: bstar
'''
import sys
from twisted.plugin import getPlugins
import ast
from dopplershift.core.containers.mediator import getMediator
from dopplershift.core.plugins.interfaces import IDSPlugin
import logging
logger = logging.getLogger(__name__)

class PluginsFactory:
    def __init__(self, default_application=''):
        
        self._plugins = {}
        self._default_application = default_application
        self._plugins[default_application] = {}
    def configure(self, config):
        for el in config.get_list(key='plugins_dir'):
            sys.path.append(el[1])
        
        self._config = config
        self.build(self._default_application)
    def build(self, application, allEnableds=False):
        self._plugins[application] = {}
        config = getMediator().get("AppConfig")
        for el in getPlugins(IDSPlugin):
            if el.application == application:
                if self.isEnabled(el, application, allEnableds) == False:
                    print "Plugin not enable %s/%s"%(el.application, el.name)
                    continue
                print "Loading plugin %s/%s [%s]"%(el.application, el.name, type(el))
                self._plugins[application][el.name] = el
                el.configure(config)
                logger.debug("plugin loaded %s/%s"%(el.application, el.name))
    def isEnabled(self, plugin, application, allEnableds=False):
        enable = self._config.get(plugin.name, 'plugin', application)
        if enable is None:
            if allEnableds ==True:return True
        else:
            if ast.literal_eval(enable) == True: return True
        return False
    def running(self):
        for el in  self._config.get("running_plugins").split(','):
            c = el.split(':')
            c.reverse()
            self.get(*c).run()
    def get(self, plugin, application=None):
        if application is None: application = self._default_application
        return self._plugins[application][plugin]
    def findall(self, application):
        return self._plugins[application].values()